package edu.android.com;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

public class dirBF extends framework{

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //Pick up the starting node
        final EditText mStartNode = (EditText)findViewById(R.id.startNode);
        Button mPickStartNode = (Button)findViewById(R.id.pickStartNode);
        
        mPickStartNode.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String str = mStartNode.getText().toString();
				
				try {
				    mmStartNode = Integer.parseInt(str);
				} catch(NumberFormatException nfe) {
				   mmStartNode = 0;
				   mStartNode.setText("");
				} 
				
				if(0 < mmStartNode && mmStartNode <= mmNrNodes)
					startThis();
				else
					mStartNode.setText("");
			}
		});
        
        setEdgePrefereces();
    }
	
	private void setEdgePrefereces(){
		edge.mOrientated = true;
		edge.mWithCost = false;
		edge.mWithFlow = false;
	}
	
	private void setDefault(){
		int len = mNodes.size();
		used = new boolean[len + 1];
		order = new int[len + 1];
		
		for(int i = 0;i <= len;i ++){
			order[i] = 0;
			used[i] = false;
		}
		
		for(int i = 0;i < len;i ++){
			mNodes.get(i).initialize();
		}
	}
	
	private void startThis(){
		setDefault();
		
		Queue <node> mQ = new LinkedList();
		mQ.add(mNodes.get(mmStartNode - 1));
		used[mmStartNode] = true;
		
		while(!mQ.isEmpty()){
			node nd = mQ.poll();
			order[++order[0]] = nd.getNodeNumber();
			
			for(int i = 0;i < nd.mEdges.size();i ++){
				node right = nd.mEdges.get(i).secondNode;
				
				if(right != nd && used[right.getNodeNumber()] == false){
					mQ.add(right);
					used[right.getNodeNumber()] = true;
				}
			}
		}
		
		showToScreen();
	}
	
	Handler handler;
	Runnable runnable;
	boolean STOP = false;
	
	private void showToScreen(){
		runnable = new Runnable() {
			public void run() {
				doStaff();
				if(STOP == false)
					handler.postDelayed(this, DELAY);
				else{
					handler.removeCallbacks(runnable);
					which = 1;
					STOP = false;
					
					showOrder();
				}
			}

		};
		handler = new Handler();
		handler.postDelayed(runnable,100);
	}
	int which = 1;
	private void doStaff(){
		mNodes.get(order[which] - 1).setUsed(Color.RED);
		mNodes.get(order[which] - 1).invalidate();
		if(which == order[0])
			STOP = true;
		which ++;
	}
	
	private void showOrder(){
		String toast = "Breadth-First Search order:\n";
		for(int i = 1;i <= order[0];i ++)
			toast = toast + order[i] + " ";
		
		mDisplayContent.setText(toast);
	}
}
